package com.cn.qgx428.lazydiary.Presenter

import android.util.Log
import com.cn.qgx428.lazydiary.Utils.FileUtil
import com.cn.qgx428.lazydiary.Utils.MConst
import com.cn.qgx428.lazydiary.Utils.ToastHelper
import com.cn.qgx428.lazydiary.network.Imageloader
import com.cn.qgx428.lazydiary.network.NetworkManager
import com.cn.qgx428.lazydiary.network.bean.*
import rx.Observable
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by qinguanxiong on 2018/3/19.
 */
class DiaryPresenter {
    companion object {

        // 创建日志
        fun createDiary(userId: Int, title: String, time: String, contents: List<DiaryContent>, listener: ()->Unit){
            // 避免中断，先上传图片数据
            // 筛选处图片数据
            val imgs: MutableList<String> = mutableListOf()
            contents.forEach {
                if (it.type.equals(MConst.DIARY_IMG_CONTENT))
                    imgs.add(it.info)
            }
            // 图片信息目前村的是文件路径， 之后只要文件名就可以了
            imgs.forEach {
                for (position in 0..contents.size - 1){
                    if (contents.get(position).type.equals(MConst.DIARY_IMG_CONTENT)
                            &&  contents.get(position).info.equals(it)){
                        contents.get(position).info = FileUtil.getFileName(it)
                    }
                }
            }
            // 有图片就过图片服务器
            if (imgs.size > 0){
                contents.forEach {
                    Log.d("lllll:  " , "${it.type}   :  ${it.info}")
                }

                var imgReady = 0
                var path = ""
                var lock = Any()
                for (i in 0..imgs.size-1){
                    path = imgs.get(i)
                    Imageloader.upload(path, FileUtil.getFileName(path), {
                        //
                        synchronized(lock,{
                            imgReady++
                            if (imgReady == imgs.size){
                                NetworkManager.getInstance()
                                        .getDiaryService()
                                        .createDiary(userId,title,time)
                                        .subscribeOn(Schedulers.newThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(object : Observer<CommonInserResponse>{
                                            override fun onError(e: Throwable?) {
                                                ToastHelper.toast("服务器错误")
                                                Log.d("what the hell d: " , e!!.message)
                                            }

                                            override fun onNext(t: CommonInserResponse?) {
                                                fillDiary(t!!.id, contents,listener)
                                            }

                                            override fun onCompleted() {

                                            }

                                        })
                            }
                        })
                    })
                }
            }


            // 没有图片，直接传
                else{
                NetworkManager.getInstance()
                        .getDiaryService()
                        .createDiary(userId,title,time)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(object : Observer<CommonInserResponse>{
                            override fun onError(e: Throwable?) {
                                ToastHelper.toast("服务器错误")
                                Log.d("what the hell d: " , e!!.message)
                            }

                            override fun onNext(t: CommonInserResponse?) {
                                fillDiary(t!!.id, contents,listener)
                            }

                            override fun onCompleted() {

                            }

                        })
            }


        }

        /**
         * 更新日志
         */
        fun updateDiary(diairyId: Int, title: String, contents: List<DiaryContent>, listener: ()->Unit){
            // 避免中断，先上传图片数据
            // 筛选处图片数据
            val imgs: MutableList<String> = mutableListOf()
            contents.forEach {
                // 已上传的图片不需重复上传
                if (it.type.equals(MConst.DIARY_IMG_CONTENT) && it.info.contains("jpg"))
                    imgs.add(it.info)
            }
            // 图片信息目前村的是文件路径， 之后只要文件名就可以了
            imgs.forEach {
                for (position in 0..contents.size - 1){
                    if (contents.get(position).type.equals(MConst.DIARY_IMG_CONTENT)
                            &&  contents.get(position).info.equals(it)){
                        contents.get(position).info = FileUtil.getFileName(it)
                    }
                }
            }
            // 有图片，上传图片
            if (imgs.size > 0){
                contents.forEach {
                    Log.d("lllll:  " , "${it.type}   :  ${it.info}")
                }

                var imgReady = 0
                var path = ""
                var lock = Any()
                for (i in 0..imgs.size-1){
                    path = imgs.get(i)
                    Imageloader.upload(path, FileUtil.getFileName(path), {
                        //
                        synchronized(lock,{
                            imgReady++
                            if (imgReady == imgs.size){
                                NetworkManager.getInstance()
                                        .getDiaryService()
                                        .updateDiary(diairyId,title)
                                        .subscribeOn(Schedulers.newThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(object : Observer<CommonResponse>{
                                            override fun onError(e: Throwable?) {
                                                ToastHelper.toast("更新失败,服务器错误")
                                                Log.d("what the hell d: " , e!!.message)
                                            }

                                            override fun onNext(t: CommonResponse?) {
                                                fillDiary(diairyId, contents,listener)
                                            }

                                            override fun onCompleted() {
                                            }
                                        })
                            }
                        })
                    })
                }
            }
            // 没有图片 , 直接更新
            else{
                NetworkManager.getInstance()
                        .getDiaryService()
                        .updateDiary(diairyId, title)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(object : Observer<CommonResponse>{
                            override fun onError(e: Throwable?) {
                                ToastHelper.toast("更新失败,服务器错误")
                                Log.d("what the hell d: " , e!!.message)
                            }

                            override fun onNext(t: CommonResponse?) {
                                fillDiary(diairyId, contents,listener)
                            }

                            override fun onCompleted() {
                            }
                        })
            }
        }

        /**
         * 添加日志内容
         */
        fun fillDiary(diaryId: Int, contents: List<DiaryContent>, listener: ()->Unit){
            var ready = 0
            val lock = Any()
            contents.forEach {
                it.diaryid = diaryId
                NetworkManager.getInstance()
                        .getDiaryService()
                        .fillDiary(diaryId, it.type, it.info, it.sequence)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(object : Observer<CommonResponse>{
                            override fun onError(e: Throwable?) {
                                ToastHelper.toast("服务器错误")
                                Log.d("what the hell d: " , e!!.message)
                            }

                            override fun onNext(t: CommonResponse?) {
                                synchronized(lock,{
                                    ready++
                                    if (ready == contents.size){
                                        listener()
                                    }
                                })
                            }

                            override fun onCompleted() {

                            }
                        })
            }
        }

        /**
         * 获取日志
         */
        fun getDiaries(userId: Int, listener: (res: DiaryResponse) -> Unit){
            NetworkManager.getInstance()
                    .getDiaryService()
                    .getDiaries(userId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<DiaryResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器错误")
                            Log.d("what the hell d: " , e!!.message)
                        }

                        override fun onNext(t: DiaryResponse?) {
                           listener(t!!)
                        }

                        override fun onCompleted() {
                        }
                    })
        }

        /**
         * 获取日志内容
         */
        fun getDiaryContent(diaryId: Int, listener: (res: DiaryContentResponse) -> Unit){
            NetworkManager.getInstance()
                    .getDiaryService()
                    .getDiaryContent(diaryId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<DiaryContentResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器错误")
                            Log.d("what the hell d: " , e!!.message)

                        }

                        override fun onNext(t: DiaryContentResponse?) {
                            listener(t!!)
                        }

                        override fun onCompleted() {
                        }
                    })
        }


        /**
         * 最近日志简介内容
         */
        fun getLatestBrife(userId: Int, listener: (res: DiaryLatestBrifeResponse) -> Unit){
            NetworkManager.getInstance()
                    .getDiaryService()
                    .getLatestBrife(userId)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Observer<DiaryLatestBrifeResponse>{
                        override fun onError(e: Throwable?) {
                            ToastHelper.toast("服务器错误")
                            Log.d("what the hell d: " , e!!.message)
                        }

                        override fun onNext(t: DiaryLatestBrifeResponse?) {
                            listener(t!!)
                        }

                        override fun onCompleted() {
                        }
                    })
        }
    }
}